package server.rest;

import org.apache.http.Header;
import org.codehaus.jackson.map.ObjectMapper;


public class JsonHttpApiClient
{

    final StringContentHttpApiClient client;
    final ObjectMapper mapper;
    final String contentType;

    public JsonHttpApiClient(StringContentHttpApiClient client, String contentType)
    {
        this.client = client;
        this.mapper = new ObjectMapper();
        this.contentType = contentType;
    }

    public StringContentHttpApiClient getClient()
    {
        return client;
    }

    public String getContentType()
    {
        return contentType;
    }
    
    public <RESPONSE> RESPONSE post(String categoryOverride, String remoteEndPoint, String pathAndQuery,
                    Object content,
                    Class<RESPONSE> responseClass, Object... parameters) throws Throwable
    {
        String json = mapper.writeValueAsString(content);
        HttpApiResponse response =
                        client.post(categoryOverride, remoteEndPoint, pathAndQuery, json, contentType, null, parameters);
        int statusCode = response.getStatusCode();
        if ((statusCode < 200) || (statusCode >= 300))
        {
            throw new Exception("Cannot deserialize when status code is not 200 level. Status code="+statusCode+", remoteEndPoint="+remoteEndPoint);
        }
        if ((responseClass!=null)&&(response.getContent() != null))
        {
            return mapper.readValue(response.getContent(), responseClass);
        }
        return null;
    }
    
    
    public <RESPONSE> RESPONSE get(String categoryOverride, String remoteEndPoint, String pathAndQuery,
                    Class<RESPONSE> responseClass, Object... parameters)
                    throws Throwable
    {
        HttpApiResponse response = client.get(categoryOverride, remoteEndPoint,pathAndQuery, null, parameters);
        int statusCode = response.getStatusCode();
        if ((statusCode < 200) || (statusCode >= 300))
        {
            throw new Exception("Cannot deserialize when status code is not 200 level. Status code="+statusCode+", remoteEndPoint="+remoteEndPoint);
        }
        if ((responseClass!=null)&&(response.getContent() != null))
        {
            return mapper.readValue(response.getContent(), responseClass);
        }
        return null;
    }
}
